package com.food.user.controller;


import cn.hutool.core.io.FileUtil;
import com.food.user.commos.Result;
import com.food.user.entity.UserAccount;
import com.food.user.exception.MyParameterException;
import com.food.user.form.*;
import com.food.user.service.UserAccountService;
import com.food.user.util.JwtUtil;
import com.food.user.util.OSSUtil;
import com.food.user.util.RedisUtil;
import com.food.user.util.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 帅得一
 * @since 2023年06月17日
 */
@RestController
@RequestMapping("/userAccount")
@Api(tags = "用户账号管理接口")
public class UserAccountController {

    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private OSSUtil ossUtil;

    @PostMapping("/register")
    @ApiOperation("手机号注册账号")
    public Result register(@RequestBody @Valid UserAccountRegisterForm form, BindingResult br) throws Exception{
        if (br.hasErrors()) {
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                //获取打印提示信息
                System.out.println(allError.getDefaultMessage());
            }
            throw new MyParameterException(500, "参数校验失败");
        }
        userAccountService.register(form);
        return Result.success(200,"手机号注册账号成功",null);
    }

    @ApiOperation("用户账号密码登录")
    @PostMapping("/login")
    private Result login(@RequestBody @Valid UserLoginForm form, BindingResult br) throws Exception {
        if (br.hasErrors()) {
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                //获取打印提示信息
                System.out.println(allError.getDefaultMessage());
            }
            throw new MyParameterException(500, "参数校验失败");
        }
        UserAccount userAccount =userAccountService.login(form);
        //登录成功后签发jwt
        HashMap<String, Object> body = new HashMap<>();
        body.put("sub",userAccount.getUserId());
        //签发短token
        String accessToken = JwtUtil.createToken(body, 30);
        //签发长token
        String refreshToken = JwtUtil.createToken(body, 8*60);
        //将长token保存到redis中
        redisUtil.setValue(accessToken,refreshToken,8*60*60L);
        //将token保存到响应头中 响应给客户端
        WebUtil.getResponse().setHeader("accessToken",accessToken);
        return Result.success(200,"登录成功！",userAccount);
    }

    @GetMapping("/sendCode")
    @ApiOperation("发送手机验证码")
    public Result sendCode(@Valid CodePhoneForm form, BindingResult br) throws Exception {
        if (br.hasErrors()) {
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                //获取打印提示信息
                System.out.println(allError.getDefaultMessage());
            }
            throw new MyParameterException(500, "参数校验失败");
        }
        userAccountService.sendCode(form);
        return Result.success(200,"发送验证码成功",null);
    }

    @PostMapping("/loginByPhone")
    @ApiOperation("手机验证码登录")
    public Result loginByPhone(@RequestBody @Valid CodePhoneLoginForm form, BindingResult br)throws Exception{
        if (br.hasErrors()) {
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                //获取打印提示信息
                System.out.println(allError.getDefaultMessage());
            }
            throw new MyParameterException(500, "参数校验失败");
        }
        UserAccount userAccount=userAccountService.loginByPhone(form);
        //登录成功后签发jwt
        HashMap<String, Object> body = new HashMap<>();
        body.put("sub",userAccount.getUserId());
        //签发短token
        String accessToken = JwtUtil.createToken(body, 30);
        //签发长token
        String refreshToken = JwtUtil.createToken(body, 8*60);
        //将长token保存到redis中
        redisUtil.setValue(accessToken,refreshToken,8*60*60L);
        //将token保存到响应头中 响应给客户端
        WebUtil.getResponse().setHeader("accessToken",accessToken);
        return Result.success(200,"手机验证码登录成功！",userAccount);
    }

    @PostMapping("/updatePassword")
    @ApiOperation("修改密码")
    public Result updatePassword(@RequestBody @Valid UpdatePasswordForm form, BindingResult br)throws Exception{
        if (br.hasErrors()) {
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                //获取打印提示信息
                System.out.println(allError.getDefaultMessage());
            }
            throw new MyParameterException(500, "参数校验失败");
        }
        userAccountService.updatePassword(form);
        return Result.success(200,"修改密码成功",null);
    }

    @PostMapping("/updateUserNickName")
    @ApiOperation("修改昵称")
    public Result updateUserNickName(@RequestBody @Valid UpdateUserNickNameForm form,BindingResult br){
        if (br.hasErrors()) {
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                //获取打印提示信息
                System.out.println(allError.getDefaultMessage());
            }
            throw new MyParameterException(500, "参数校验失败");
        }
        userAccountService.updateUserNickName(form);
        return Result.success(200,"修改账号昵称成功",null);
    }

    @GetMapping("/showMyAccount")
    @ApiOperation("查询个人账号信息")
    public Result showMyAccount(){
        UserAccount userAccount=userAccountService.showMyAccount();
        return Result.success(200,"查询个人账号信息成功",userAccount);
    }

    @GetMapping("/out")
    @ApiOperation("退出当前登录用户")
    public Result out(){
        userAccountService.out();
        return Result.success(200,"退出当前登录用户成功",null);
    }

    @PostMapping("/upload")
    @ApiOperation("上传头像")
    public Result uploadUserImg(MultipartFile file) throws Exception{
        //MultipartFile重要API
        InputStream is = file.getInputStream();//获取文件内容
        String filename = file.getOriginalFilename();//获取文件名称
        //取出后缀名
        String suffix = FileUtil.getSuffix(filename);
        filename= UUID.randomUUID().toString().replaceAll("-","");
        String url = ossUtil.uploadFile(is, filename + "." + suffix, "woniu-food-tyy");

        UserAccount userAccount = userAccountService.showMyAccount();
        userAccount.setUserImg(url);
        userAccountService.saveOrUpdate(userAccount);
        return Result.success(200,"上传图片成功",url);
    }

}

